<template>
  <div class="hello-page">
    <Spin :spinning="loading.state.value">
      <template #indicator><LoadingOutlined /></template>
      <Transition name="fade-fast" mode="out-in">
        <input
          v-if="inputState.isEdit"
          key="login"
          type="password"
          id="password"
          class="input"
          autofocus
          :disabled="loading.state.value"
          :value="inputState.value"
          @input="handleInputChange($event)"
          @blur="quitEdit"
          @keydown.capture="handleInputKeyDown($event)"
        />
        <div v-else class="title" key="show" @click="toEditMode" @touchend="toEditMode">🤘</div>
      </Transition>
    </Spin>
  </div>
</template>

<script lang="ts" setup>
import { reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Spin } from 'ant-design-vue'
import { LoadingOutlined } from '@ant-design/icons-vue'
import { authLogin } from '@/store/auth'
import tokenService from '@/services/token'

import { useLoading } from '@/handcer'

const loading = useLoading()
const router = useRouter()
const inputState = reactive({
  value: '',
  isEdit: false,
  spinning: false,
})

// 登录
const login = (password: string) => {
  loading
    .promise(authLogin(password))
    .then((newAuth) => {
      tokenService.setToken(newAuth.access_token, newAuth.expires_in)
      router.push('/dashboard')
    })
    .catch((error) => {
      console.warn('登陆系统失败！', error)
      return Promise.reject(error)
    })
}

// 修改登录输入
const handleInputChange = (event: Event) => {
  inputState.value = (event.target as any).value
}

// 回车
const handleInputKeyDown = (event: KeyboardEvent) => {
  if (event.key === 'Escape') {
    quitEdit()
  }
  if (event.key === 'Enter') {
    if (inputState.value) {
      login(inputState.value)
    }
  }
}

// 退出输入
const quitEdit = () => {
  inputState.isEdit = false
}

// 切换模式
const toEditMode = () => {
  inputState.isEdit = true
}
</script>

<style lang="less" scoped>
.hello-page {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  .title {
    width: 6rem;
    height: 6rem;
    border-radius: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 38px;
    background-color: #141414;
    user-select: none;
    cursor: pointer;
  }

  .input {
    display: block;
    width: 30rem;
    height: 6rem;
    padding: 2rem;
    border-radius: 8px;
    background-color: rgba(20, 20, 20, 1);
    font-size: 38px;
    text-align: center;
    color: #fff;
    border: none;
    outline: none;
  }
}
</style>
